<!-- eslint-disable vue/multi-word-component-names -->
<template >
	<div class="upload">
		<el-upload
			action="#"
			list-type="picture-card"
			ref="upload"
			:before-upload="beforeUpload"
			:limit="limit"
			:auto-upload="false"
			:on-remove="handleRemove"
			:on-exceed="handleExceed"
			:on-change="change"
			:file-list="fileList"
		>
			<i slot="default" class="el-icon-plus"></i>
		</el-upload>
	</div>
</template>
<script>
	import axios from 'axios'
	export default {
		data() {
			return {
				imageUrl: '',
				imgUrl: '',
				headerObj: {
					Authorization: localStorage.getItem('token'),
				},
			}
		},
		props: {
			limit: {
				type: Number,
				default: 50,
			},
			fileList: {
				type: Array,
				default: function () {
					return []
				},
			},
		},
		methods: {
			beforeUpload(file) {
				if (file) {
					const suffix = file.name.split('.')[1]
					const size = file.size / 1024 / 1024 < 2
					if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
						this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
						this.$refs.upload.clearFiles()
						return false
					}
					if (!size) {
						this.$message.error('上传文件大小不能超过 2MB!')
						return false
					}
					return file
				}
			},
			async upload() {
				let url = '/api/rear-end/common/upload'
				let formData = new FormData()
				if (this.$refs.upload._data.uploadFiles.length > 0) {
					formData.append('file', this.$refs.upload._data.uploadFiles[0].raw)
					const res = await axios.post(url, formData, {
						headers: {
							'Content-Type': 'multipart/form-data',
							Authorization: localStorage.getItem('token'),
						},
					})
					this.$emit('img', res.data.data)
				} else {
					this.$emit('img', '')
				}
				return
			},
			handleRemove(file) {
				const index = this.fileList.findIndex((item) => item.name === file.name)
				if (index !== -1) {
					this.$emit('updatafileList', index)
				}
			},
			handleRemove1() {
				this.$refs.upload.clearFiles()
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url
				this.dialogVisible = true
			},
			handleExceed(files, fileList) {
				this.$message.warning(
					`当前限制选择${this.limit} 个文件，本次选择了 ${
						files.length
					} 个文件，共选择了 ${files.length + fileList.length} 个文件`
				)
			},
			change(){
				this.$emit('check', true)
			}
		},
	}
</script>
<style scoped>
	.avatar {
		width: 147px;
		height: 147px;
		display: block;
		position: absolute;
		margin-top: -147px;
	}
</style>